/**
 * 令牌桶算法 对业务
 * @author huangliusong
 * @since 2019/1/15
 * {@link }
 */
public class TokenBucket {

    private int bucketNums=100;

    private int rate=1;

    private int nowTokens;

    private long timestamp =getNowTime();


    private int min(int tokens){
        if(bucketNums>tokens){
            return tokens;
        }else {
            return bucketNums;
        }
    }

    private long getNowTime(){
        return System.currentTimeMillis();
    }

    public boolean getToken(){
        //记录来拿令牌的时间
        long nowTime=getNowTime();
        //添加令牌-判断有多少令牌
        nowTokens=nowTokens+(int)((nowTime-timestamp)*rate);
        //添加以后的令牌数量和桶的容量哪个小
        nowTokens=min(nowTokens);
        System.out.println("当前令牌数量："+nowTokens);
        //update time
        timestamp=nowTime;
        //if it's enough
        if (nowTokens<1){
             return false;
        }else {
            nowTokens-=1;
            return true;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        TokenBucket tokenBucket=new TokenBucket();
        for (int i=0;i<100 ;i++){
            if (i==10){
                Thread.sleep(5000);
            }
            System.out.println("第"+i+"次请求结果"+tokenBucket.getToken());
        }
    }

}
